<template>
  <div class="app-container">
    <!-- 操作 -->
    <div class="crud">
      <div class="crud-left">
        <el-button v-if="role_list.indexOf('80000060201') != -1" class="fill-btn" @click="handleUpdate(-1, 'create')">添加</el-button>
        <el-button v-if="role_list.indexOf('80000060203') != -1" class="plain-btn" @click="handleDelmultip">删除</el-button>
        <el-button class="plain-btn" @click="resetfilter">重置</el-button>
        <el-button class="plain-btn reset-btn" @click="scanning">扫描</el-button>
        <div class="input-box">
          <span class="item-label">所属网点</span>
          <addr-branch ref="parent_cascader" :select_level="1" @changenode=" changeBranch" />
        </div>
        <div class="input-box">
          <span class="item-label">所属公司</span>
          <el-select class="group-select" v-model="listQuery.groupIds" filterable reserve-keyword placeholder="选择公司"
            @change="changeGroup" clearable>
            <el-option v-for="item in list_group" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
        </div>

      </div>
      <div class="search">
        <el-input v-model="listQuery.keyword" placeholder="查找设备" class="crud-input">
          <el-button class="search-btn" slot="append" icon="el-icon-search" @keyup.enter.native="handleFilter" @click="handleFilter" />
        </el-input>
      </div>
    </div>

    <!-- 0 table表格 -->
    <el-table :key="tableKey" v-loading="listLoading" element-loading-text="数据加载中" element-loading-spinner="el-icon-loading"
      :data="list" border fit highlight-current-row style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="expand" width="55">
        <template slot-scope="{ row }">
          <el-table :key="child_level2" v-loading="listLoading" :data="row.channels || []" border fit
            highlight-current-row style="width: 100%; background_color: #ffd">
            <el-table-column label="通道名称" align="center">
              <template slot-scope="{ row }">
                <div v-if="row.Pedit_inline" class="temp-input">
                  <el-input v-model="row.name" class="edit-input" size="small" />
                </div>
                <span v-else>{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <div class="online-status" :class="
                    scope.row.online == 1 ? 'status-active' : 'status-inactive'
                  "></div>
                <span :class="scope.row.online == 1 ? '' : 'status-text-inactive'">{{ scope.row.online == 1 ? "在线" : "离线" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="国标ID" show-overflow-tooltip align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.gbId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="账号名" align="center">
              <template slot-scope="{ row }">
                <div v-if="row.Pedit_inline" class="temp-input">
                  <el-input v-model="row.username" class="edit-input" size="small" />
                </div>
                <span v-else>{{ row.username }}</span>
              </template>
            </el-table-column>
            <el-table-column label="密码" align="center">
              <template slot-scope="{ row }">
                <div v-if="row.Pedit_inline" class="temp-input">
                  <el-input v-model="row.password" class="edit-input" size="small" />
                </div>
                <span v-else>{{ row.password }}</span>
              </template>
            </el-table-column>
            <el-table-column label="端口号" align="center">
              <template slot-scope="{ row }">
                <div v-if="row.Pedit_inline" class="temp-input">
                  <el-input v-model="row.port" class="edit-input" size="small" />
                </div>
                <span v-else>{{ row.port }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center">
              <template slot-scope="{ row }">
                <div v-if="row.Pedit_inline" class="temp-input">
                  <el-input v-model="row.remark" class="edit-input" size="small" :maxlength="60" type="textarea" placeholder="请输入内容"
                    show-word-limit />
                </div>
                <span v-else>{{ row.remark }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template slot-scope="{ row }">
                <template v-if="row.Pedit_inline">
                  <span class="action action-update" @click="Pcancel(row)">取消</span>
                  <span> | </span>
                  <span class="action action-update" @click="Ppreservation(row)">保存</span>
                </template>
                <template v-else>
                  <span class="action action-update" @click="row.Pedit_inline = !row.Pedit_inline">编辑</span>
                  <span class="action action-update" style="margin-left: 5px;" @click="Pdelete(row)">删除</span>
                </template>
              </template>
            </el-table-column>

          </el-table>
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="55" label="序号" />
      <el-table-column label="设备名称" min-width="140" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.edit_inline" class="temp-input">
            <el-input v-model="row.name" class="edit-input" size="small" />
          </div>
          <span v-else>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" class-name="status-col" width="150">
        <template slot-scope="{ row }">
            <div class="online-status" :class="row.enable == 1 ? 'status-inactive' : 'status-active'"></div>
            <span :class="row.enable == 1 ? '' : 'status-text-inactive'">{{
            row.online == 1 ? "正常" : "禁用"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" class-name="status-col" width="140" prop="isOnline" :filters="status_filter"
        :filter-method="filterHandler">
        <template slot-scope="{ row }">
          <!-- <i class="iconfont icon-dian online-status"></i> -->
          <div class="online-status" :class="row.online == 1 ? 'status-active' : 'status-inactive'"></div>
          <span :class="row.online == 1 ? '' : 'status-text-inactive'">{{
            row.online == 1 ? "在线" : "离线"
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="设备账号" show-overflow-tooltip min-width="140" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.edit_inline" class="temp-input">
            <el-input v-model="row.username" class="edit-input" size="small" />
          </div>
          <span v-else>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备密码" show-overflow-tooltip min-width="140px" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.edit_inline" class="temp-input">
            <el-input v-model="row.password" class="edit-input" size="small" />
          </div>
          <span v-else>{{ row.password }}</span>
        </template>
      </el-table-column>
      <el-table-column label="IP" min-width="120px" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.edit_inline" class="temp-input">
            <el-input v-model="row.ip" class="edit-input" size="small" />
          </div>
          <span v-else>{{ row.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="端口" min-width="90px" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.edit_inline" class="temp-input">
            <el-input v-model="row.port" class="edit-input" size="small" />
          </div>
          <span v-else>{{ row.port }}</span>
        </template>
      </el-table-column>
      <el-table-column label="国标ID" show-overflow-tooltip min-width="140" align="center"  width="200">
        <template slot-scope="{ row }">
          <span>{{ row.gbId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通道数" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.channels ? row.channels.length : 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="240px" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.edit_inline" class="temp-input">
            <el-input v-model="row.remark" class="edit-input" size="small" :maxlength="60" type="textarea" placeholder="请输入内容"
              show-word-limit />
          </div>
          <span v-else>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接入协议" align="center" width="140">
        <template slot-scope="{ row }">
          <span v-if="row.protocol == 1">国标</span>
          <span v-else-if="row.connectType == 2">私有</span>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.type == 1">IPC</span>
          <span v-else-if="row.type == 2">NVR</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" sortable min-width="140px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" min-width="140px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updateTime | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{ row }">
          <template v-if="row.edit_inline">
            <span class="action action-update" @click="cancelEditLine(row)">取消</span>
            <span> | </span>
            <span class="action action-update" @click="updateDataInline(row)">保存</span>
          </template>
          <span v-else-if="role_list.indexOf('80000060202') != -1" class="action action-update" @click="handleUpdate(row, 'update')">编辑</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 1 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 2 添加或修改的弹框 -->
    <el-dialog :title="dialogStatus=='create'? '添加设备':'编辑设备'" :visible.sync="dialogFormVisible" width="60%" :close-on-click-modal="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
        <div class="formitem-container">
          <el-form-item prop="siteId">
            <span slot="label" class="form-item-label">所属网点</span>
            <addr-branch ref="add_parent_cascader" v-if="dialogStatus == 'create'" :select_level="1" @changenode="handleAddr" />
            <el-select v-else v-model="temp.siteId" filterable reserve-keyword placeholder="选择网点" style="width: 100%" clearable>
              <el-option v-for="item in list_branch" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item prop="protocol">
            <span slot="label" class="form-item-label">设备协议</span>
            <el-select v-model="temp.protocol" filterable reserve-keyword placeholder="接入协议" style="width: 100%" clearable :disabled="dialogStatus == 'update'">
              <el-option v-for="item in list_connectType" :key="item.proId" :label="item.proName + ' ' + item.remark" :value="item.proId" />
            </el-select>
          </el-form-item>

          <el-form-item prop="name">
            <span slot="label" class="form-item-label">设备名称</span>
            <el-input v-model="temp.name" type="text" maxlength="18" placeholder="设备名称" />
          </el-form-item>

          <el-form-item prop="type">
            <span slot="label" class="form-item-label">设备类型</span>
            <el-select v-model="temp.type" filterable reserve-keyword placeholder="设备类型" style="width: 100%" clearable :disabled="dialogStatus == 'update'">
              <el-option v-for="item in list_type" :key="item.typeId" :label="item.typeName + ' ' + item.remark" :value="item.typeId" />
            </el-select>
          </el-form-item>

          <el-form-item prop="username">
            <span slot="label" class="form-item-label">设备账号</span>
            <el-input v-model="temp.username" type="text" maxlength="25" placeholder="设备账号" />
          </el-form-item>

          <el-form-item prop="password">
            <span slot="label" class="form-item-label">设备密码</span>
            <el-input :key="password_type_reg" ref="password_reg" v-model="temp.password" :type="password_type_reg"
              placeholder="设备密码" name="password_reg" tabindex="6" autocomplete="off" clearable @keyup.native="checkCapslock(0, $event)"
              @blur="reg_tooltip = false">
              <span slot="append" class="show-pwd" @click="showPwd(0)">
                <svg-icon :icon-class="
                    password_type_reg === 'password' ? 'eye' : 'eye-open'
                  " />
              </span>
            </el-input>
          </el-form-item>

          <el-form-item prop="ip">
            <span slot="label" class="form-item-label">IP地址</span>
            <el-input v-model="temp.ip" type="text" maxlength="18" placeholder="IP地址" />
          </el-form-item>

          <el-form-item prop="port">
            <span slot="label" class="form-item-label">端口号</span>
            <el-input v-model="temp.port" type="text" maxlength="18" placeholder="端口号" />
          </el-form-item>

          <el-form-item>
            <span slot="label" class="form-item-label">选择厂商</span>
            <el-select v-model="temp.firm" filterable reserve-keyword placeholder="选择厂商" style="width: 100%" clearable>
              <el-option v-for="item in list_firm" :key="item.firmId" :label="item.firmName + ' ' + item.remark" :value="item.firmId" />
            </el-select>
          </el-form-item>

          <el-form-item prop="resGroupId" v-if="dialogStatus == 'create'">
            <span slot="label" class="form-item-label">设备组</span>
            <el-select v-model="temp.resGroupId" filterable reserve-keyword placeholder="选择设备资源组" style="width: 100%" clearable>
              <el-option v-for="item in list_resourceGroup" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <span slot="label" class="form-item-label">高度</span>
            <el-input v-model="temp.height" type="text" maxlength="18" placeholder="摄像头的高度" />
          </el-form-item>

          <el-form-item>
            <span slot="label" class="form-item-label">经度</span>
            <el-input v-model="temp.longitude" type="text" maxlength="18" placeholder="经度" />
          </el-form-item>

          <el-form-item>
            <span slot="label" class="form-item-label">纬度</span>
            <el-input v-model="temp.latitude" type="text" maxlength="18" placeholder="纬度" />
          </el-form-item>

          <el-form-item prop="">
            <span slot="label" class="form-item-label">填写备注</span>
            <el-input v-model="temp.remark" type="text" maxlength="18" placeholder="填写备注" />
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="dialogFormVisible = false">取消</el-button>
        <el-button class="fill-dialog-btn" @click="dialogStatus === 'create' ? createData() : updateData()">确认</el-button>
      </div>
    </el-dialog>
    <!-- 3 删除的提示框 -->
    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center>
      <div class="del-data del-img">
        <img :src="require('../../assets/img/del.png')" alt="" />
      </div>
      <div class="del-data del-notify">确定对设备进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="fill-dialog-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>
    <!-- 4 状态更改的提示框 -->
    <el-dialog :visible.sync="dialogToggle" title="提示" width="30%" center>
      <div class="del-data del-img">
        <img :src="require('../../assets/img/remind.png')" alt="" />
      </div>
      <div class="del-data del-notify">确定对状态进行【更改】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="handleCancel(sta_row)">取消</el-button>
        <el-button class="fill-dialog-btn" @click="toggleStatus(sta_row)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import waves from "@/directive/waves"; // waves directive
  import {
    parseTime
  } from "@/utils"; // 解析时间
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import AddrSelect from "@/components/Address/AddrSelect";
  import {
    deviceAdd,
    deviceDel,
    deviceUpdate,
    devicescanning,
    deviceList,
    deviceListconnectType,
    deviceDeleteChannel,
    devicelisttype,
    devicelistfirm,
    deviceStatus,
    deviceModifyChannel,
    deviceProtocol,
    branchList } from "@/api/branch";
  import {userSelectRole,    resourceList} from "@/api/permission";
  import AddrBranch from "@/components/Address/AddrBranchSelect.vue";

  import {
    validPass,
    validlongitude,
    validlatitude,
    validaltitude
  } from "@/utils/validate";
  import {
    logger
  } from "runjs/lib/common";


  const calendarTypeOptions = [{
      key: "CN",
      display_name: "China",
    },
    {
      key: "US",
      display_name: "USA",
    },
    {
      key: "JP",
      display_name: "Japan",
    },
    {
      key: "EU",
      display_name: "Eurozone",
    },
  ];

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
  }, {});

  export default {
    name: "BranchDevice",
    components: {
      Pagination,
      AddrSelect,
      AddrBranch,
    },
    directives: {
      waves,
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "info",
          deleted: "danger",
        };
        return statusMap[status];
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type];
      },
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        if (!validPass(value)) {
          callback(new Error("8~16位,包含大小写字母和数字, 可以有特殊字符"));
        } else {
          callback();
        }
      }

      // 校验高度
      const validatealtitude= (rule, value, callback) => {
        if (!validaltitude(value)) {
          callback(new Error("请输入正确高度"));
        } else {
          callback();
        }
      }

      // 校验经度
      const validatelongitude = (rule, value, callback) => {
        if (!validlongitude(value)) {
          callback(new Error("经度整数部分应为0~180,小数部分为0~6位"));
        } else {
          callback();
        }
      }

      // 校验纬度
      const validatelatitude = (rule, value, callback) => {
        if (!validlatitude(value)) {
          callback(new Error("纬度整数部分为0-90,小数部分为0~6位"));
        } else {
          callback();
        }
      }

      return {
        multipleSelection: [],
        is_multip: false, // 是否批量删除
        tableKey: 0,
        child_level2: 0,
        // list: null,
        list: [],
        total: 0, // 总条数
        listLoading: false,
        listQuery: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: "", // 搜索关键字
          groupIds: "", // 公司种类
          siteId: "", // 网点id
          node_code: "", // 地区节点id
          level: "", // node 的等级
          province_code: "",
          city_code: "",
          area_code: "",
          street_code: "",
        },
        calendarTypeOptions,
        temp: {
          name: "", //设备名称
          ip: "", //IP地址
          port: "", //端口
          username: "", //用户名
          password: "", //密码
          protocol: "", //协议类型,1(国标)2(私有)
          siteId: "", // 网点id
          type: "", //设备类型,1(IPC)2(NVR)
          enable: "", //设备是否可用
          longitude: "", //经度
          latitude: "", //纬度
          height: "", //高度
          firm: "", //厂商名称
          resGroupId: "", //资源组
          remark: "", //备注
          channels: [   //这个是通道，目前不用填写
            {
              id: "",
              deviceId: 0,
              name: "",
              ip: "",
              port: 0,
              username: "",
              password: "",
              enable: false,
              online: false,
              longitude: 0.0,
              latitude: 0.0,
              height: 0.0,
              remark: "",
            },
          ],
        },
        sta_row: {}, // 修改状态值, 保存当前数据
        dialogFormVisible: false,
        dialogStatus: "",
        del_id: "",
        del_index: null,
        dialogPvVisible: false, // 删除提示框
        dialogToggle: false, // 状态更改的提示框
        rules: {
          password: [{
            required: true,
            trigger: "blur",
            message: '密码不能为空',
          }, ],
          username: [{
            required: true,
            trigger: "blur",
            message: '账户不能为空',
          }, ],
          protocol: [{
            required: true,
            trigger: "change",
            message: "请选择协议",
          }, ],
          name: [{
            required: true,
            trigger: "blur",
            message: "请填写设备名称",
          }, ],
          type: [{
            required: true,
            trigger: "change",
            message: "请选择设备类型",
          }, ],
          ip: [{
            required: true,
            trigger: "blur",
            message: "请填写IP地址",
          }, ],
          port: [{
            required: true,
            trigger: "blur",
            message: "请填写端口号",
          }, ],
          firm: [{
            required: true,
            trigger: "change",
            message: "请选择厂商",
          }, ],
          resGroupId : [{
            required: true,
            trigger: "change",
            message: "请选择资源组",
          }, ],
          height: [{
            required: true,
            trigger: "blur",
            validator: validatealtitude
          }, ],
          longitude: [{
            required: true,
            trigger: "blur",
            validator: validatelongitude
          }, ],
          latitude: [{
            required: true,
            trigger: "blur",
            validator: validatelatitude
          }, ],
          siteId: [{
            required: true,
            message: "请选择网点",
            trigger: "change"
          }, ]
        },

        
        list_connectType: [],   // 设备协议
        list_type: [],   // 设备类型        
        list_firm: [],   // 厂商        
        list_resourceGroup: [],   // 设备资源组
        list_approve: [{id: 0, label: "不需认证"}, {id: 1, label: "密码认证"}],
        list_character: [{id: 1, label: "UTF-8"}, {id: 2, label: "GB2312"}, {id: 3, label: "GBK"}],
        list_group: [{id: "", label: "全部"}, {id: 11, label: "邮政"}, {id: 12, label: "圆通"}, { id: 13, label: "申通"}, { id: 14, label: "中通"}, { id: 15, label: "韵达"}, { id: 16, label: "顺丰"}],   // 所属公司
        list_branch: [], // 所属网点
        list_role: [], // 角色列表

        password_type_reg: "password",
        password_type_reg2: "password",
        reg_tooltip: false, // 大写 ?
        reg2_tooltip: false, // 大写 ?
        status_filter: [{text: "在线",value: 1}, {text: "离线", value: 0}], // 过滤设备的状态
        role_list: [], // 按钮权限
      };
    },
    watch: {},
    created() {
      this.getList()
    },
    mounted() {
      this.getBranchList();
      this.getRoleList();
      this.role_list = this.$store.getters.menu_code_list;
      this.getListconnectType()
      this.getlisttype()
      this.getlistfirm()
      this.getlResourceGroup()
    },
    methods: {
      // 通道取消
      Pcancel(row, is_cancel = true) {
        row.name = row.original_name
        row.username = row.original_username
        row.password = row.original_password
        row.port = row.original_port
        row.remark = row.original_remark

        row.Pedit_inline = !row.Pedit_inline;
        this.child_level2 = Math.random()

        if (is_cancel) {
          this.$message({
            message: "已经取消更改",
            type: "warning",
          });
        }
      },
      // 通道保存
      Ppreservation(row) {
        deviceModifyChannel(
          {
            id: row.id,
            name: row.name,
            username: row.username,
            password: row.password,
            port: row.port,
            remark: row.remark
          }
        )
        .then((res) => {
          console.log('修改通道成功数据 :>> ', res);
          this.$notify({
            title: "成功",
            message: "修改通道成功",
            type: "success",
            duration: 4000,
          })
          row.edit_inline = false;
          this.child_level2 = Math.random()
          this.getList()
        })
        .catch((res) => {
          this.$message({
            message: "网络错误",
            type: "error",
          })
        })
      },
      // 通道删除
      Pdelete(row) {
        console.log('通道删除 :>> ', row);

        deviceDeleteChannel(
          {
            deviceId: row.deviceId,
            channelIds: row.id
          }
        )
        .then((res) => {
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 4000,
          })
          this.getList()
        })
        .catch((res) => {
          this.$message({
            message: "网络错误",
            type: "error",
          })
        })
      },
      // 设备协议(下拉回显)
      getListconnectType() {
        deviceListconnectType().then((res) => {
          this.list_connectType = res.data
        })
      },
      // 设备类型(下拉回显)
      getlisttype() {
        devicelisttype().then((res) => {
          this.list_type = res.data
        })
      },
      // 厂商(下拉回显)
      getlistfirm() {
        devicelistfirm().then((res) => {
          this.list_firm = res.data
        })
      },
      getlResourceGroup() {
        resourceList().then((res) => {
          let list_resource = res.data || []
          list_resource.forEach((item) => {
            if(item.groupType == 1) {
              this.list_resourceGroup.push(item)
            }
          })
        })
      },
      // 重置过滤条件
      resetfilter() {
        this.listQuery = {
          page: 1,
          limit: 10,
          keyword: "",
          groupIds: "",
          siteId: "",
          node_code: "",
          level: "",
          province_code: "",
          city_code: "",
          area_code: "",
          street_code: "",
        };
        this.$refs["parent_cascader"].clearNodes();
        this.getList();
      },

      // 获取 table 列表=============================================
      getList() {
        this.listLoading = true;

        console.log('当前页码 :>> ', this.listQuery.page);

        let temp_query = {
          offset: this.listQuery.page,
          limit: this.listQuery.limit,
          keyword: this.listQuery.keyword,
          groupIds: this.listQuery.groupIds,
          siteId: this.listQuery.siteId,
        };
        if (this.listQuery.level == 1)
          temp_query.provinceCodes = this.listQuery.province_code;
        else if (this.listQuery.level == 2)
          temp_query.cityCodes = this.listQuery.city_code;
        else if (this.listQuery.level == 3)
          temp_query.areaCodes = this.listQuery.area_code;
        else if (this.listQuery.level == 4)
          temp_query.streetCodes = this.listQuery.street_code;

        deviceList(temp_query)
          .then((res) => {
            if (res.code == 0) {
              if (res.data) {
                this.list = res.data.list;
                this.total = parseInt(res.data.totalCount);
                // this.list = this.list.map((item, i) => {
                //   return item;
                // });
              } 
              else {
                this.list = []
              }
              this.listLoading = false;
            }
            else {
              this.listLoading = false;
              this.$message({
                message: "请求失败",
                type: "error",
              });
            }
          })
          .catch((res) => {
            this.listLoading = false;
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },

      // 网点列表( 下拉回显)
      getBranchList() {
        branchList().then((res) => {
          if (res.code == 0) {
            this.list_branch = res.data || [];
          }
        });
      },

      // 获取角色列表 (下拉回显)
      getRoleList() {
        userSelectRole().then((res) => {
          this.list_role = res.data || [];
        });
      },


      // 添加用户时:  选择网点
      handleAddr(code, level, newval) {
        this.temp.siteId = code;
      },

      // 点击了 状态值切换==========================
      changeStatus(row) {
        this.dialogToggle = true;
        this.sta_row = row;
      },
      // 确认了  状态值切换
      toggleStatus(row) {
        console.log('状态值 :>> ', row);
        deviceUpdate({
            id: row.id,
            enable: row.enable,
          })
          .then((res) => {
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: "状态修改成功",
                type: "success",
                duration: 4000,
              });
              this.dialogToggle = false;
            } else {
              row.enable = row.original_enable;
              this.$message({
                message: "状态修改失败",
                type: "error",
              });
            }
          })
          .catch((res) => {
            row.enable = row.original_enable;
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },
      // 取消状态管理
      handleCancel(row) {
        this.dialogToggle = false;
      },

      // 监听是否打开了大写
      checkCapslock(num, e) {
        const {
          key
        } = e;
        if (num == 0) {
          // 注册账号: 设置密码
          this.reg_tooltip = key && key.length === 1 && key >= "A" && key <= "Z"; // 若开启大写则提示文字
        } else if (num == 1) {
          // 注册账号: 再次输入密码
          this.reg2_tooltip = key && key.length === 1 && key >= "A" && key <= "Z"; // 若开启大写则提示文字
        }
      },
      // 是否显示密码
      showPwd(num) {
        if (num == 0) {
          this.password_type_reg === "password" ?
            (this.password_type_reg = "") :
            (this.password_type_reg = "password");
          this.$nextTick(() => {
            // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg.focus();
          });
        } else if (num == 1) {
          this.password_type_reg2 === "password" ?
            (this.password_type_reg2 = "") :
            (this.password_type_reg2 = "password");
          this.$nextTick(() => {
            // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg2.focus();
          });
        }
      },

      // 扫描设备
      scanning() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: "没有被选项!",
            type: "error",
            duration: 4000,
            showClose: true,
            center: true,
          });
        } 
        else {
          let ids = [];
          if (this.multipleSelection.length == 1) {
            ids = [this.multipleSelection[0].id];
          } else {
            this.multipleSelection.forEach((item, i) => {
              ids.push(item.id);
            });
          }

          console.log('参数 :>> ', ids);
          devicescanning(ids).then(res => {
            if(res.code == 0) {
                this.getList()
                this.$notify({
                  title: '成功',
                  message: '扫描成功',
                  type: 'success',
                  duration: 4000
                })
              }
              else {
                this.$message({
                  message: '扫描失败',
                  type: 'error'
                })
              }
          })
        }
      },

      // 点击了 '编辑' 或 '添加'  设备======================================================
      handleUpdate(row, str) {
        if (str == "create") this.resetTemp(); // 清空
        if (str == "update") {
          this.temp = Object.assign({}, row); // 克隆一个对象
          this.temp.firm = parseInt(this.temp.firm)
        }
        this.dialogStatus = str;

        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      },
      // 编辑: 确认更新数据
      updateData() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            this.temp.gbId = undefined
            deviceUpdate(this.temp).then(() => {
              // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
              // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
              this.getList();
              // this.resetfilter()
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: "更新成功",
                type: "success",
                duration: 4000,
              });
            });
          } else {
            return false;
          }
        });
      },
      // 确认添加
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            deviceAdd(this.temp).then(res => {
              console.log('成功返回 :>> ', res);
              if(res.code == 0) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 4000
                })
              }
              else {
                this.$message({
                  message: '添加失败',
                  type: 'error'
                })
              }
            }).catch( res => {
              this.$message({
                message: '网络错误',
                type: 'error'
              })
            })
          }
          else {
            return false;
          }
        })
      },
      // 清空temp
      resetTemp() {
        this.temp = {
          name: "", //设备名称
          ip: "", //IP地址
          port: "", //端口
          username: "", //用户名
          password: "", //密码
          protocol: "", //协议类型,1(国标)2(私有)
          siteId: "", // 网点id
          type: "", //设备类型,1(IPC)2(NVR)
          enable: "", //设备是否可用
          longitude: "", //经度
          latitude: "", //纬度
          height: "", //高度
          firm: "", //厂商名称
          remark: "", //备注
          channels: [
            //这个是通道，目前不用填写
            {
              id: "",
              deviceId: 0,
              name: "",
              ip: "",
              port: 0,
              username: "",
              password: "",
              enable: false,
              online: false,
              longitude: 0.0,
              latitude: 0.0,
              height: 0.0,
              remark: "",
            },
          ],
        };
      },
      // 点击了删除===============================================
      handleDelete(row, index) {
        this.is_multip = false;
        this.del_id = row.id;
        this.del_index = index;
        this.dialogPvVisible = true;
      },
      // 点击了 批量删除
      handleDelmultip() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: "没有被选项!",
            type: "error",
            duration: 4000,
            showClose: true,
            center: true,
          });
        } else {
          this.is_multip = true;
          this.dialogPvVisible = true;
        }
      },
      // 确认了删除
      delData() {
        let ids = [];
        if (this.is_multip) {
          // 批量删
          this.multipleSelection.forEach((item, i) => {
            ids.push(item.id);
          });
        } else {
          ids = [this.del_id];
        }
        deviceDel(ids).then(() => {
          this.dialogPvVisible = false;
          // this.list.splice(this.del_index, 1)
          this.getList();
          // this.resetfilter()

          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 4000,
          });
        });
      },

      // 筛选条件的切换 (地区切换)
      changeAddr(cut_node, cut_level, newval) {
        if (cut_level == 1) {
          this.listQuery.province_code = cut_node;
          this.listQuery.level = cut_level;
        } else if (cut_level == 2) {
          this.listQuery.city_code = cut_node;
          this.listQuery.level = cut_level;
        } else if (cut_level == 3) {
          this.listQuery.area_code = cut_node;
          this.listQuery.level = cut_level;
        } else if (cut_level == 4) {
          this.listQuery.street_code = cut_node;
          this.listQuery.level = cut_level;
        }
        this.getList();
      },

      // 筛选条件的切换 (公司切换)------------------------------
      changeGroup() {
        this.getList();
      },
      // 改变用的
      changeGroupHandle() {
        this.getBranchListHandle();
      },
      // 筛选条件的切换 (网点切换)
       changeBranch(code, level, newval) {
        this.listQuery.siteId = code;
        this.getList()
      },

      // 搜索
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      // 批量选择
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 设备的过滤
      filterHandler(value, row, column) {
        const property = column["property"];
        return row[property] == value;
      },
    },
  };
</script>

<style lang="scss">
  @import "~@/styles/variables.scss";

  .crud {
    // .el-input-group__append {
    //   color: var(--app_primary);
    //   border: 0;
    //   border-left: 1px solid var(--app_primary);

    //   .el-button {
    //     // height: 27px;
    //     // border: 1px solid $my_primary !important;
    //     // background-color: #f11;
    //   }
    // }
  }

  .el-dialog {
    .el-dialog__header {
      background-color: #f5f7f5 !important;
    }
  }

  .formitem-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .el-form-item {
      width: 49%;
    }
  }

  .el-form-item__label {
    // 两端对齐
    display: flex;
    justify-content: space-between;
    align-items: center !important;

    &::before {
      transform: translateY(3px);
    }

    .form-item-label {
      flex: 1;
      text-align-last: justify !important;
      text-align: justify !important;
    }
  }
</style>


<style lang="scss" scoped>
  @import "~@/styles/variables.scss";
  @import "~@/styles/element-variables.scss";

  .app-container {
    padding: 10px;
    background-color: #ffffff;

    .crud {
      margin-bottom: 32px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .crud-left {
        // background-color: #faa;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .reset-btn {
          margin-right: 15px;
        }
      }
    }

    // background-color: #f99 !important;
    .el-table {
      .online-status {
        display: inline-block;
        height: 7px;
        width: 7px;
        border-radius: 50%;
        margin-right: 5px;
        transform: translateY(-2px);
      }

      .status-active {
        background-color: var(--app_primary);
      }

      .status-inactive {
        background-color: $my_danger;
      }

      .status-text-inactive {
        color: $text_light;
      }

      .action {
        font-size: 13px;
        color: var(--app_primary);
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;

        img {
          width: 130px;
          height: 110px;
        }
      }

      .del-img {}
    }
  }
</style>
